import React, { useState, useImperativeHandle, RefObject, useEffect } from 'react';

import { Modal, Form, Input, Tree, message } from 'antd';
import type { TreeDataNode } from 'antd';


import { IRole, IPermission } from '../../types/role';
import { IMenu } from '../../types/login';
import role from '../../api/role';
import api from '../../api/index';

interface IProps {
  deptRef: RefObject<{
    showModal: (
      type: string,
      data?: IRole,
    ) => void,
  }>;
  upData: () => void;
}

const App: React.FC<IProps> = (props) => {
  // 控制弹窗显示隐藏
  const [isModalOpen, setIsModalOpen] = useState(false);
  // action: add 新增 edit 编辑 set 设置权限
  const [action, setAction] = useState<string>('add');
  // 选中权限
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  // 权限列表
  const [menuList, setMenuList] = useState<IMenu[]>();
  // 选中列信息
  const [roleInfo, setRoleInfo] = useState<IRole>()
  // 设置权限
  const [editPermissionList, setEditPermissionList] = useState<IPermission>({
    _id: '',
    permissionList: { checkedKeys: [], halfCheckedKeys: [] }
  });
  // 表单
  const [form] = Form.useForm();
  // 显示弹窗
  const showModal = (type: string, data?: IRole,) => {
    setAction(type);
    if (type === 'set') {
      setRoleInfo(data as IRole)
      setCheckedKeys(data?.permissionList.checkedKeys || [])
      setEditPermissionList({
        _id: data?._id || '',
        permissionList: {
          checkedKeys: data?.permissionList.checkedKeys || [],
          halfCheckedKeys: data?.permissionList.halfCheckedKeys || []
        }
      })
    } else form.setFieldsValue(data);
    setIsModalOpen(true);
  };


  const onCheck = (checked: any, info: any) => {
    console.log(checked, info);
    setCheckedKeys(checked)
    const checkedKeys: string[] = []
    const halfCheckedKeys: string[] = []
    info.checkedNodes.map((item: IMenu) => {
      if (item.menuType === 2) checkedKeys.push(item._id)
      else halfCheckedKeys.push(item._id)
    })
    setEditPermissionList({
      _id: roleInfo?._id || '',
      permissionList: {
        checkedKeys,
        halfCheckedKeys
      }
    })

  }

  // 保存
  const handleOk = () => {
    if (action === 'set') {
      role.setPermission(editPermissionList).then(() => {
        message.success('保存成功');
        handleCancel()
        props.upData();
      })

    } else {
      // 校验form
      form.validateFields().then(async () => {
        if (action === 'add') await role.addRole(form.getFieldsValue());
        else if (action === 'edit') await role.editRole(form.getFieldsValue());
        message.success('保存成功');
        handleCancel()
        props.upData();
      })
    }


  };
  // 取消
  const handleCancel = () => {
    form.resetFields();
    setIsModalOpen(false);
  };

  // 获取权限列表
  const getPermissionList = async () => {
    const data = await api.getMenuList();
    setMenuList(data);
  };


  useEffect(() => {
    getPermissionList();
  }, []);

  useImperativeHandle(props.deptRef, () => ({
    showModal
  }));

  return (
    <>
      <Modal
        title={
          action === 'add' ? '新增部门' : action === 'set' ? '设置权限' : '编辑部门'
        }
        width={800}
        maskClosable={false}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
      >
        <Form form={form} preserve={false} labelAlign="right" labelCol={{ span: 4 }}>
          <Form.Item noStyle shouldUpdate>
            {
              () => {
                if (action === 'set') {
                  return (
                    <>
                      <Form.Item label="角色名称"></Form.Item>
                      <Form.Item label="权限">
                        <Tree
                          checkable
                          onCheck={onCheck}
                          defaultExpandAll
                          checkedKeys={checkedKeys}
                          fieldNames={{
                            key: '_id',
                            children: 'children',
                            title: 'menuName',
                          }}
                          treeData={menuList as unknown as TreeDataNode[]}
                        />
                      </Form.Item>
                    </>
                  );
                } else {
                  return (
                    <>
                      <Form.Item
                        label="角色名称"
                        name="roleName"
                        rules={[{ required: true, message: '请输入角色名称' }]}
                      >
                        <Input />
                      </Form.Item>
                      <Form.Item
                        label="备注"
                        name="remark"
                      >
                        <Input.TextArea />
                      </Form.Item>
                    </>
                  );
                }

              }
            }


          </Form.Item>

        </Form>
      </Modal>
    </>
  );
};

export default App;